<template>
  <div>
    <div class="form-label">小题数：{{form.items.length}}</div>
    <draggable :list="form.descrips" handle=".mover">
      <div class="question-desc">
        <el-tag effect="dark" size="mini">01</el-tag>
        <div class="question-desc-label">题目描述：</div>
        <div class="question-desc-editor">
          <div v-for="(item, i) in form.descrips" :key="i" class="question-desc-editor-item">
            <div class="question-desc-editor-head">
              <el-select v-model="item.type" :disabled="readOnly" size="mini">
                <el-option
                  v-for="optItem in descOptions"
                  :key="optItem.value"
                  :label="optItem.label"
                  :value="optItem.value">
                </el-option>
              </el-select>
              <div v-if="!readOnly" class="question-desc-del">
                <i class="el-icon-delete"></i><span @click="() => removeDescribe(i)">移除项目描述</span>
              </div>
            </div>
            <editor v-if="item.type === 'fulltext'" v-model="item.content" :readOnly="readOnly" :min-height="180"/>
          </div>
        </div>
        <div class="mover">
          <i class="el-icon-rank mover-icon"></i>
        </div>
      </div>
    </draggable>
    <div v-if="!readOnly" class="desc-more">
      <i class="el-icon-plus" style="color: #409eff"></i><span @click="addDescribe">添加题目描述</span>
    </div>
    <div v-if="!readOnly" class="add-basic">
      <div class="add-basic-btn">
        <el-button type="primary" size="small" @click="addBasic">添加小题</el-button>
      </div>
      <div class="basic-btn">
        <el-radio-group v-model="curBasicQuestion">
          <el-radio-button v-for="item in basicOptions" :key="item.value" :label="item.value">{{item.label}}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div v-for="(item, index) in form.items" :key="index" class="basic-item">
      <div class="basic-item-head">
        <span>第{{wordList[index]}}小题：{{parseBasic(item.formCode)}}</span>
        <div class="right-icon">
          <i class="el-icon-error font-16" @click="() => delBasic(index)"></i>
          <i class="el-icon-arrow-down font-16"></i>
        </div>
      </div>
      <div class="basic-detail">
        <div class="common-choice">
          <div class="common-choice-item">
            <div class="item-label">题干:</div>
            <div v-for="(subItem, i) in item.descrips" :key="i" class="edit-wrap">
              <editor v-model="subItem.content" :readOnly="readOnly" :min-height="180"/>
            </div>
          </div>
        </div>
        <single-choice
          v-if="item.formCode == 'SingleSelect'"
          :initialVals="tmpItems[index]"
          :clean="clean"
          :readOnly="readOnly"
          @change="qs => handleQuestionChange(qs, index)"
          @onValid="handleValid"
        />
        <multi-choice
          v-if="item.formCode == 'MultiSelect'"
          :initialVals="tmpItems[index]"
          :clean="clean"
          :readOnly="readOnly"
          @change="qs => handleQuestionChange(qs, index)"
          @onValid="handleValid"
        />
        <completion
          v-if="item.formCode == 'FillBlank'"
          :initialVals="tmpItems[index]"
          :clean="clean"
          :readOnly="readOnly"
          @change="qs => handleQuestionChange(qs, index)"
          @onValid="handleValid"
        />
        <judge
          v-if="item.formCode == 'TrueFalse'"
          :initialVals="tmpItems[index]"
          :clean="clean"
          :readOnly="readOnly"
          @change="vhandleQuestionChange(qs, index)"
          @onValid="handleValid"
        />
        <short-answer
          v-if="item.formCode == 'ShortAnswer'"
          :initialVals="tmpItems[index]"
          :clean="clean"
          :readOnly="readOnly"
          @change="qs => handleQuestionChange(qs, index)"
          @onValid="handleValid"
        />
      </div>
    </div>
    <div class="answer">
      <div class="answer-title">
        <el-checkbox v-model="form.isAnalysis" :disabled="readOnly" :true-label="1" :false-label="0">答案解析</el-checkbox>
      </div>
      <div class="third-indent">
        <editor v-model="form.analysis" :readOnly="readOnly" :min-height="180"/>
      </div>
    </div>
    <el-form ref="form" :model="form" label-width="62px">
      <el-form-item label="难度" prop="difficulty">
        <el-select v-model="form.difficulty" :disabled="readOnly" placeholder="请选择难度" clearable size="small">
          <el-option
            v-for="dict in dict.type.question_difficulty"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="知识点" prop="pointId">
        <el-select v-model="form.pointIds" :disabled="readOnly" placeholder="请选择知识点" multiple clearable size="small">
        <el-option
          v-for="item in pointData"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import { getTree } from "@/api/resourceEditor/publicResourceManagement";
import SingleChoice from './singleChoice.vue';
import MultiChoice from './multiChoice.vue';
import Completion from './completion.vue';
import Judge from './judge.vue';
// 简答或缩写题
import ShortAnswer from './shortAnswer.vue';
import Sortable from './sortable.vue';
import Connector from './connector.vue';
import ShareChoice from './shareChoice.vue';

export default {
  name: "Basic",
  dicts: ['question_difficulty'],
  props: {
    initialVals: {
      type: Object,
      default: () => ({}),
    },
    clean: {
      type: String,
      default: '',
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    validate: {
      type: String,
      default: '',
    },
  },
  components: {
    draggable,
    SingleChoice,
    MultiChoice,
    Completion,
    Judge,
    ShortAnswer,
    Sortable,
    Connector,
    ShareChoice
  },
  data() {
    return {
      form: {
        descrips: [{
          type: 'fulltext',
          content: ''
        }],
        items: []
      },
      tmpItems: [],
      descOptions: [
        { value: 'fulltext', label: '富文本' },
        { value: 'radio', label: '音频文件' },
        { value: 'video', label: '视频文件' },
      ],
      basicOptions: [
      { value: 'SingleSelect', label: '单选题' },
      { value: 'MultiSelect', label: '多选题' },
      { value: 'FillBlank', label: '填空题' },
      { value: 'TrueFalse', label: '判断题' },
      { value: 'ShortAnswer', label: '简答题' },
      ],
      curBasicQuestion: '',
      wordList: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
      pointData: []
    }
  },
  watch: {
    initialVals: {
      handler(val) {
        if (Object.keys(val).length > 0) {
          this.form = { ...this.form, ...val };
          this.tmpItems = val.items;
        }
      },
      immediate: true,
    },
    clean: {
      handler(val) {
        if (val) {
          const tmpForm = JSON.parse(JSON.stringify(this.form));
          delete tmpForm.items;
          this.form = tmpForm;
        }
      }
    },
    validate: {
      handler(val) {
        if (val) {
          // TODO: 表单验证通过则往上传递事件
          this.$emit('onChange', this.form);
        }
      }
    }
  },
  created() {
    this.fetchKnowledge();
  },
  methods: {
    // 获取知识点列表
    fetchKnowledge() {
      getTree('').then(({ code, data }) => {
        if (code === 200) {
          this.pointData = data.rows.map(item => ({ label: item.name, value: item.id }));
        }
      });
    },
    onClose() {
      this.$emit('update:open', false);
    },
    // 取消按钮
    cancel() {
      onClose();
    },
    // 添加题目描述
    addDescribe() {
      this.form.descrips.push({
        type: 'fulltext',
        content: ''
      });
    },
    removeDescribe(i) {
      this.form.descrips.splice(i, 1);
    },
    parseBasic(code) {
      const result = this.basicOptions.find(item => item.value == code);
      return result ? result.label : '';
    },
    // 添加小题
    addBasic() {
      if (this.curBasicQuestion) {
        const item = {
          formCode: this.curBasicQuestion,
          descrips: [{ type: 'fulltext', content: '' }]
        }
        this.form.items.push(item);
        this.tmpItems = JSON.parse(JSON.stringify(this.form.items));
      } else {
        this.$message({
          message: '请选择小题',
          type: 'warning'
        });
      }
    },
    delBasic(i) {
      this.form.items.splice(i, 1);
      this.tmpItems = JSON.parse(JSON.stringify(this.form.items));
    },
    // 同步内外层表单
    handleQuestionChange(qs, i) {
      const innerForm = JSON.parse(JSON.stringify(qs));
      delete innerForm.firstLevelType;
      delete innerForm.secondLevelType;
      const item = this.form.items[i];
      const descrips = JSON.parse(JSON.stringify(item.descrips));
      this.form.items[i] = { ...item, ...innerForm, descrips };
    },
    // 内层表单校验结果
    handleValid(isValid) {
      console.log(isValid);
    },
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
  